package com.zhiwei.msf.gateway.filter;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.Charset;

import javax.servlet.http.HttpServletRequest;

import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.zhiwei.msf.common.util.HttpUtil;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

/**
 * function: 记录请求响应
 * author: zhiwei_yang
 * time: 2020/2/11-18:37
 */
@Component
@Slf4j
public class LoggerFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.SEND_RESPONSE_FILTER_ORDER - 2;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @SneakyThrows
    @Override
    public Object run() {
        RequestContext requestContext = RequestContext.getCurrentContext();
        InputStream responseDataStream = requestContext.getResponseDataStream();
        String responseBody = StreamUtils.copyToString(responseDataStream, Charset.defaultCharset());

        HttpServletRequest httpServletRequest = requestContext.getRequest();
        log.info("===> 请求URI:[{}], 请求头:[{}], 参数:[{}] 响应 ==> {}",
                requestContext.getRequest().getRequestURI(), HttpUtil.getRequestParamsStr(httpServletRequest),
                HttpUtil.getRequestHeaderMap(httpServletRequest), responseBody);

        //字节流单向流动，重新设置字节流到过滤器上下文，返回客户端响应
        requestContext.setResponseDataStream(new ByteArrayInputStream(responseBody.getBytes(Charset.defaultCharset())));
        return null;
    }
}